<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>待办事项</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css"/>
</head>
<body>
<div class="jumbotron jumbotron-fluid">
    <div class="container text-center">
        <h1 class="display-4">JavaScript ToDo</h1>
        <p class="lead">待办事项</p>
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-12">
            <form action="" class="mb-5" onsubmit="return false">
                <div class="form-group">
                    <input id="ipt" type="text" class="form-control" placeholder="在此输入任务...">
                </div>

                <button id="btn" type="submit" class="btn btn-primary btn-block">添加</button>
            </form>
            <ul class="list-group" id="ul"></ul>
        </div>
    </div>
</div>


<script>
    let lists=["学习 JavaScript","学习 css3","学习 HTML5"];

    function d(){
        document.querySelector("#ul").innerHTML="";
        for(let i=0;i<lists.length;i++){
            let li=document.createElement('li');
            li.className="list-group-item d-flex justify-content-between align-items-center";

            let span=document.createElement("span");
            let spanText=document.createTextNode(lists[i]);
            span.appendChild(spanText);

            //先给span设置为不可编辑状态
            span.setAttribute("contenteditable",false);

            //给span加失去焦点事件
            span.addEventListener('dblclick',function(){
                //span设置为可编辑状态
            span.setAttribute("contenteditable",true);
            });
            //span加失去焦点事件
            span.addEventListener('blur',function(){
                //span设置为不可编辑状态
                span.setAttribute("contenteditable",false)
            });
            li.appendChild(span);

            let button=document.createElement('button');
            button.type='button';
            button.classList.add('close');
            button.innerHTML='&times;';

            //给button加事件
            button.addEventListener('click',function(){
                lists.splice(i,1);
                //点击后，再重新渲染一遍DOM
                d()
            });
            li.appendChild(button);

            let ul=document.querySelector('#ul');
            ul.appendChild(li);
        }
    }
    //默认先循环一遍数组内容
    d();

    let but=document.querySelector("#btn");
    but.addEventListener('click',function(){
        let text=document.querySelector("#ipt");
        if (text.value !=""){
            lists.unshift(text.value);
            text.value="";
        }else {
            alert("不可以为空");
        }

        //执行for循环
        d();
    })
</script>
</body>
</html>